﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;

using LEEAAttendanceControl.Web;
using LEEAAttendanceControl.Web.Services;

using System.ServiceModel.DomainServices.Client;

using System.Collections.ObjectModel;

using System.Windows.Browser;
using System.ServiceModel;
using System.ComponentModel;

using LEEAAttendanceControl.AttendanceReference;
using LEEAAttendanceControl.General;

namespace LEEAAttendanceControl.Views
{
    public partial class ExceptionAssignments : Page
    {
        LEEAContext context = new LEEAContext();

        private CheckBox checkAllBox = null;

        Dictionary<int, string> departments = new Dictionary<int, string>();

        ObservableCollection<int> employees = new ObservableCollection<int>();

        Dictionary<int, KeyValuePair<DateTime, int>> exceptions = new Dictionary<int, KeyValuePair<DateTime, int>>();
        
        public ExceptionAssignments()
        {
            InitializeComponent();

            ChangeEmployees();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            App myApp = (App)Application.Current;

            myApp.ClearEvents();

            myApp.ChangeEmployeesEvent += ChangeEmployeesHandler;

            ChangeEmployees();
        }

        public void ChangeEmployeesHandler(object sender, EventArgs e)
        {
            ChangeEmployees();
        }
        
        void ChangeEmployees()
        {
            if (checkAllBox != null && checkAllBox.IsChecked.Value)
            {
                checkAllBox.IsChecked = false;
            }

            EmployeesGrid.ItemsSource = null;

            context.EmployeeSummaries.Clear();

            int companyID = ((App)Application.Current).CompanyID ?? 0;

            int departmentID = ((App)Application.Current).DepartmentID ?? 0;

            int employeeID = ((App)Application.Current).EmployeeId;

            context.Load(context.GetEmployeeSummariesForExceptionsQuery(companyID, departmentID, employeeID)
                , OnEmployeesLoadCompleted, null);
        }

        private void OnEmployeesLoadCompleted(LoadOperation load)
        {
            EmployeesGrid.ItemsSource = load.Entities;
        }

        private void SelectAllCheckBox_Click(object sender, RoutedEventArgs e)
        {
            employees.Clear();

            CheckBox selector = sender as CheckBox;

            if (checkAllBox == null)
            {
                checkAllBox = selector;
            }

            foreach (var item in EmployeesGrid.ItemsSource)
            {
                EmployeeSummary emp = item as EmployeeSummary;

                emp.IsChecked = selector.IsChecked.Value;

                if (selector.IsChecked.Value)
                {
                    employees.Add(emp.EmployeeID);
                }
            }
        }

        private void EmployeeCheck_Click(object sender, RoutedEventArgs e)
        {
            CheckBox rowCheck = sender as CheckBox;

            EmployeeSummary emp = EmployeesGrid.SelectedItem as EmployeeSummary;

            if (rowCheck.IsChecked.Value)
            {
                employees.Add(emp.EmployeeID);
            }
            else
            {
                employees.Remove(emp.EmployeeID);

                if (checkAllBox != null && checkAllBox.IsChecked.Value)
                {
                    checkAllBox.IsChecked = false;
                }
            }
        }

        private void ApplyButton_Click(object sender, RoutedEventArgs e)
        {
            foreach (var item in ExceptionsGrid.ItemsSource)
            {
                Exeption exception = item as Exeption;

                DatePicker startPicker = ExceptionsGrid.Columns[1].GetCellContent(item) as DatePicker;

                NumericUpDown durationUD = ExceptionsGrid.Columns[2].GetCellContent(item) as NumericUpDown;

                if (startPicker.SelectedDate != null)
                {
                    exceptions[exception.ID] = new KeyValuePair<DateTime, int>(startPicker.SelectedDate.Value
                        , (int) durationUD.Value);
                }
            }

            foreach (int emp in employees)
            {
                foreach (int exception in exceptions.Keys)
                {
                    context.ExceptionAssignments.Add(new ExceptionAssignment()
                        {
                            EmployeeID = emp,
                            ExceptionID = exception,
                            DateFrom = exceptions[exception].Key,
                            DateTo = exceptions[exception].Key.AddDays(exceptions[exception].Value - 1)
                        });
                }
            }

            context.SubmitChanges(OnAssignmentsSubmitted, null);
        }

        private void OnAssignmentsSubmitted(SubmitOperation operation)
        {
            if (operation.HasError)
            {
                operation.MarkErrorAsHandled();
                MessageDisplay message = new MessageDisplay(ApplicationStrings.GeneralError
                    , ApplicationStrings.GeneralError, "Error");

                message.Show();
            }
            else
            {
                NavigationService.Navigate(new Uri("/Views/EmployeesExceptions.xaml", UriKind.Relative));
            }
        }

        private void ClearButton_Click(object sender, RoutedEventArgs e)
        {
            DatePicker startPicker = ExceptionsGrid.Columns[1].GetCellContent(ExceptionsGrid.SelectedItem)
                as DatePicker;

            NumericUpDown durationUD = ExceptionsGrid.Columns[2].GetCellContent(ExceptionsGrid.SelectedItem)
                as NumericUpDown;

            startPicker.SelectedDate = null;

            durationUD.Value = 1;
        }
    }
}